package pers.corvey.crawler.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import pers.corvey.crawler.dao.CelebrityDAO;
import pers.corvey.crawler.dao.MovieCelebrityDAO;
import pers.corvey.crawler.dao.MovieDAO;
import pers.corvey.crawler.extract.CelebrityExtract;
import pers.corvey.crawler.model.Celebrity;
import pers.corvey.crawler.model.Movie;
import pers.corvey.crawler.model.MovieCelebrity;
import pers.corvey.crawler.model.json.CelebrityJson;
import pers.corvey.crawler.transformer.CelebrityTransformer;

@Service
public class CelebrityServiceImpl implements CelebrityService {
	
	@Autowired
	private MovieDAO movieDAO;

	@Autowired
	private CelebrityDAO celebrityDAO;
	
	@Autowired
	private MovieCelebrityDAO movieCelebrityDAO;
	
	public Celebrity crawlById(String id) throws Exception {
		CelebrityJson json = CelebrityExtract.getCelebrityById(id);
		Celebrity celebrity = CelebrityTransformer.toCelebrity(json);
		save(celebrity);
		return celebrity;
	}
	
	private void save(Celebrity celebrity) throws Exception {
		if (celebrity == null) {
			return ;
		}
		celebrityDAO.save(celebrity);
		List<Movie> movies = celebrity.getWorks(); 
		if (movies != null && movies.size() != 0) {
			movieDAO.saveAll(movies);
			List<MovieCelebrity> works = MovieCelebrity.create4Work(celebrity);
			movieCelebrityDAO.saveAll(works);
		}
	}
}
